<!--
 * @description  : 市管-特殊区域计划制定
 * @descriptionDetail: 市管-特殊区域计划制定
 * @copyright    : 浙江烟草
 * @author       : sy
 * @create       : 2022-09-26 15:57:44
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar
      :is-white="false"
      :title="navTitle"
      :custom-back="goBack"
      style="z-index: 99999"
    >
    </theme-navbar>
    <!-- #endif -->
    <u-toast ref="uToast" />
    <u-form :model="planForm" :rules="rules" :errorType="errorType" style="padding: 0px 15px;" ref="uForm">
      <u-form-item left-icon="calendar" required label="计划日期" prop="planDate" :label-width="180" right-icon="arrow-right">
        <u-input input-align="right" :custom-style="valueStyle" placeholder="请选择计划日期" :disabled="true" v-model="planForm.planDate" @tap="!isDisabled && (dateShow=true)" />
      </u-form-item>
      <u-form-item left-icon="man-add" required label="执行人" prop="executorNames" :label-width="180" right-icon="arrow-right">
        <u-input style="flex: 1;" input-align="right" :custom-style="valueStyle" placeholder="请选择执行人" :disabled="true" v-model="planForm.executorNames" @tap="!isDisabled && (orgPersonSelectShow=true)" />
      </u-form-item>
      <u-form-item left-icon="tags" required label="是否专项行动" prop="isSpecialAction" :label-width="220">
        <view class="market_cs">
          <u-switch v-model="planForm.isSpecialAction" :disabled="isDisabled" @change="actionChange"></u-switch>
        </view>
      </u-form-item>
      <u-form-item v-if="planForm.isSpecialAction" left-icon="man-add" required label="关联专项行动" :label-width="220" right-icon="arrow-right" prop="actionName">
        <u-input style="flex: 1;" input-align="right" :custom-style="valueStyle" placeholder="请选择关联专项行动" :disabled="true" v-model="planForm.actionName" @tap="!isDisabled && addActionRelation()" />
      </u-form-item>
      <u-form-item left-icon="account" label="制定人" :label-width="180">
        <u-input input-align="right" :custom-style="valueStyle" :disabled="true" v-model="planForm.operator" />
      </u-form-item>
      <u-form-item left-icon="order" label="工作内容描述" label-position="top">
        <u-input type="textarea" :disabled="isDisabled" v-model="planForm.workContent" />
      </u-form-item>
    </u-form>
    <view class="divider-info">
      检查区域<u-tag class="client-num" type="primary" :text="clients.length" shape="circle" />
      <span class="sub-info" v-if="!isDisabled">(向左滑动删除)</span>
      <u-icon style="float:right;" :color="$theme.u_type_primary" name="plus" size="38" v-if="!isDisabled" @click="handlerDoMore()"></u-icon>
    </view>
    <view class="card" v-for="(item, index) in clients" :key="item.areaUuid">
      <u-swipe-action
        :index="index"
        :show="item.show"
        :options="options"
        :disabled="isDisabled"
        @click="handlerDeleteClient(item)"
        @open="handlerOpen(index)"
      >
        <areas-item :isClick="false" :client="item"></areas-item>
      </u-swipe-action>
    </view>
    <view class="space-content"></view>
    <!-- 底部按钮开始 -->
    <view class="submit-btns btn-other-cls" v-if="!isDisabled">
      <u-button plain class="u-btn" type="primary" :loading="submitBtnLoading" @click="handlerDoSubmit(M_PLAN_STATUS.DRAFT)">
        保存
      </u-button>
      <u-button class="u-btn" type="primary" :loading="submitBtnLoading" @click="handlerDoSubmit(M_PLAN_STATUS.SUBMITTED)">
        发布
      </u-button>
    </view>
    <!-- 底部按钮结束 -->
    <!-- 检查日期 -->
    <u-calendar :min-date="getMinDate()" :mode="mode" max-date="9999-12-31" v-model="dateShow" @change="calendarChange"></u-calendar>
    <!-- 执行人 -->
    <u-popup mode="bottom" border-radius="14" height="80%" v-model="personShow">
      <multi-select :leftBtnOpt="leftBtnOpt" :options="personOptions" @select="handlerSelectPersons"></multi-select>
    </u-popup>
    <!-- 执行人选择更多 -->
    <u-popup mode="bottom" height="80%" v-model="orgPersonSelectShow">
      <org-person-select treeType="zm-user" modelType="market" @choose="handlerChoosePerson"></org-person-select>
    </u-popup>
  </view>
</template>
<script>
import multiSelect from '@/components/multi-select.vue';
import checkService from "@/service/check/check.service"
import commonService from "@/service/common/common.service";
import AreasItem from './components/areas-item.vue';
import OrgPersonSelect from "@/components/org-person-select.vue";
import {M_PLAN_STATUS,} from "@/service/check/mapping/enum.js";
export default {
  components: { multiSelect, AreasItem,OrgPersonSelect, },
  data() {
    return {
      M_PLAN_STATUS,
      dateShow: false,  // 日期选择
      checkDate: "",    // 检查日期
      nowDay: this.$u.date(Date.now(),'yyyy-mm-dd'),
      mode: "date",
      valueStyle: {
        marginRight: "5px",
      },
      errorType: ['border-bottom','message',],
      planForm: {
        planDate: '',
        executorNames:'',
        actionName: '',
        actionUuid: '',
        isSpecialAction: false,
      },
      rules: {
        planDate: [
          {
            required: true,
            message: '请选择检查日期',
            trigger: ['change','blur',],
          },
        ],
        executorNames: [
          {
            required: true,
            message: '请选择执行人',
            trigger: ['change','blur',],
          },
        ],
        actionName:[
          {
            required: true,
            message: '请选择关联专项行动',
            trigger: ['change','blur',],
          },
        ],
      },
      planTypeShow: false,
      personShow: false,
      orgPersonSelectShow:false,
      personOptions: [],
      selectPersons: [],
      clients: [],  // 选中的检查户
      options: [
        {
          text: '删除',
          style: {
            backgroundColor: '#dd524d',
          },
        },
      ],
      leftBtnOpt:{
        isBack:true,
        backText:"更多选择",
        backIconName:"man-add",
        backFun:() => {},
      },
      submitBtnLoading: false,  // 提交按钮显示加载
      plan: this.getRouteParam() || {}, // 计划数据
      isDisabled: false,
    }
  },
  onShow() {

  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  mounted() {
    // this.$refs.uForm.setRules(this.rules);
    this.leftBtnOpt.backFun = (pItems) => {
      this.personShow = false;
      this.selectPersons = pItems;
      this.orgPersonSelectShow = true;
    };
  },
  created() {
    this.initPlan();
    // 查询执行人
    this.$u.loading("加载中...");
    checkService.findDayPlanExecutorList().then(dr => {
      this.$u.hideLoading();
      if (dr.success) {
        let ps = dr.data;
        ps.map(p => {
          p.uid = p.personUuid;
          p.name = p.personName;
          p.exts = [p.inspectionCertNo,];
        });
        this.$nextTick(() => this.personOptions = ps);
      }
    }).catch((err) => {
      this.$u.toast(err);
      this.$u.hideLoading();
    });
  },
  methods: {
    initPlan() {
      // 调用详情接口
      if(this.plan.checkPlanUuid){
        this.queryPlanData();
      }else{
        // 新制定计划
        this.planForm = Object.assign({}, this.plan);
        !this.planForm.operator && (this.planForm.operator = this.curUser.user.personName);
        !this.planForm.planDate && (this.planForm.planDate = this.nowDay);
        this.isDisabled = this.plan.checkPlanUuid && this.plan.status != this.M_PLAN_STATUS.DRAFT;
      }
    },
    // 选择执行人
    handlerChoosePerson(psrList){
      this.orgPersonSelectShow = false;
      psrList = psrList.filter(itm => {
        for (let i = 0; i < this.selectPersons.length; i++) {
          if(this.selectPersons[i].personUuid == itm.id){
            return false;
          }
        }
        return true;
      });
      let newList = psrList.map((item) => {
        return {
          personUuid:item.id,
          personName:item.name,
        }
      });
      this.selectPersons = [...this.selectPersons,...newList,];
      let pNames = [];
      let pIds = [];
      this.selectPersons.forEach(p => {
        pNames.push(p.personName);
        pIds.push(p.personUuid);
      });
      this.planForm.executorNames = pNames.join(",");
      this.planForm.executors = pIds.join(",");
    },
    getMinDate(){
      return this.$u.timeFormat(Date.now());
    },
    // 日历选择时调用
    calendarChange(d){
      this.planForm.planDate = d.result;
    },
    actionChange(val){
      if(!val){
        this.planForm.actionName = '';
        this.planForm.actionUuid = '';
      }
    },
    // 关联专项行动
    addActionRelation(){
      this.$u.route('/pages/check/specialActionRelationList');
    },
    // 根据页面返回的参数处理相应逻辑
    updateBackState(param){
      console.log(param);
      let list = [];
      let actionObj;
      // 添加特殊区域任务
      if(param['specialAreasTask']){
        list = param['specialAreasTask'];
      } else if(param['specialAction']){
        // 选择专项行动
        actionObj = param['specialAction'][0];
        // 专项行动赋值
        this.planForm.actionUuid = actionObj.actionUuid;
        this.planForm.actionName = actionObj.actionName;
      }
      // 判断特殊区域任务是否有重复的
      list.forEach(c => {
        if (this.clients.filter(r => r.areaUuid == c.areaUuid).length > 0) {
          this.$u.toast(`【${c.areaName}】已存在`);
        } else {
          this.clients.push(c);
        }
      });

      this.$forceUpdate();
      console.log(this.planForm);
      let newList = [...this.selectPersons,];
      let obj = {};
      let result = newList.reduce((item,next) => {
        obj[next.personUuid] ? '' : obj[next.personUuid] = true && item.push(next)
        return item
      },[]);
      this.selectPersons = newList;
      console.log(result);

    },
    // 查询计划详情
    queryPlanData() {
      this.$u.loading("加载中...");
      checkService.getCheckPlanDetail({checkPlanUuid:this.plan.checkPlanUuid,}).then(dr => {
        this.$u.hideLoading();
        if (dr.success) {
          this.planForm = dr.bean;
          this.planForm.isSpecialAction = dr.bean.isSpecialAction == '1' ? true : false;
          // this.planForm.isReportHotline = dr.bean.isReportHotline == '1' ? true : false;
          // this.planForm.userName = this.plan.userName;
          // this.selectPersons = dr.bean.executorList;
          this.clients = dr.bean.specialAreaList;
          this.isDisabled = this.planForm.checkPlanUuid && this.planForm.status != this.M_PLAN_STATUS.DRAFT;
        }
      }).catch((er) => {
        this.$u.hideLoading();
        this.$u.toast(er);
      });
    },
    // 执行人
    handlerSelectPersons(pItems) {
      this.personShow = false;
      this.selectPersons = pItems;
      let pNames = [];
      let pIds = [];
      this.selectPersons.forEach(p => {
        pNames.push(p.name);
        pIds.push(p.id);
      });
      this.planForm.executorNames = pNames.join(",");
      this.planForm.executors = pIds.join(",");
    },
    // 删除选中的客户
    handlerDeleteClient(cItem) {
      this.clients = this.clients.filter(c => c.areaUuid != cItem.areaUuid);
    },
    handlerOpen(idx) {
      this.clients.map((c, i) => {
        c.show = i == idx;
      });
      this.$forceUpdate();
    },
    // 检查显示更多
    handlerDoMore() {
      this.setRouteParam(this.clients);
      // 添加特殊区域任务
      this.$u.route('/pages/check/specialAreasTask?checkDate=' + this.planForm.planDate);
    },
    // 保存或发布
    handlerDoSubmit(status) {
      this.$refs.uForm.validate(valid => {
        if (valid) {
          if (this.clients.length == 0) {
            this.$u.toast("请选择检查区域");
            return;
          }
          this.$modal.confirm(`确定${status == M_PLAN_STATUS.SUBMITTED ? '发布' : '保存'}吗？`, () => {
            this.$u.loading(`${status == M_PLAN_STATUS.SUBMITTED ? '发布' : '保存'}中...`);
            let planData = {
              planDate: this.planForm.planDate,
              executorNames: this.planForm.executorNames,
              executors: this.planForm.executors,
              status: status,
              checkPlanUuid: this.plan.checkPlanUuid || "",
              specialAreaList:this.clients,
              workContent: this.planForm.workContent,
              isSpecialAction: this.planForm.isSpecialAction ? '1' : '0', // 是否专项行动
              actionUuid: this.planForm.isSpecialAction ? this.planForm.actionUuid : "",
              actionName:this.planForm.isSpecialAction ? this.planForm.actionName : "",
              // isReportHotline:this.planForm.isReportHotline ? '1' : '0', // 是否12313
              isReportHotlineName:this.planForm.isReportHotline ? '是' : '否',
            };
            checkService.saveOrUpDateCheckPlan(planData).then(dr => {
              this.$u.hideLoading();
              if (dr.success) {
                this.backPrev({
                  paramKey: "refresh",
                  param : true,
                });
              } else {
                this.$u.toast(dr.msg);
              }
            });
          });
        } else {
          console.error('验证失败');
        }
      });
    },
  },
}
</script>
<style lang="scss" scoped>
.page{padding: 0;}
.divider-info {
  font-size: 16px;
  margin: 5px 15px 10px 15px;
  color: #333;
  font-weight: 600;
  .sub-info {
    font-weight: 100;
    font-size: 14px;
    color: #000;
  }
}
.page {
  padding-bottom: 55px;
}
.client-num {
  padding: 3px 5px;
  font-weight: bold;
  margin: 0px 5px;
  font-size: 14px;
}
.bottom-btns {
  position: fixed;
  bottom: 0px;
  width: 100%;
  background-color: #f8f8f8;
  //padding: 5px 0px;
}
.market_cs {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}
// h5端部分浏览器input设置disabled后点击事件失效 2023-10-24 fsx start
	/deep/.uni-input-input {
		pointer-events: none !important;
	}
	// h5端部分浏览器input设置disabled后点击事件失效 2023-10-24 fsx end
</style>
